package top.hmtools.jsCss.cssManager;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import top.hmtools.jsCss.autoConfiguration.JsCssAutoConfiguration;
import top.hmtools.jsCss.common.ResourcesBean;

/**
 * css相关操作controller
 * @author HyboJ
 * 创建日期：2017-9-27下午4:52:40
 */
@Controller
//@ConditionalOnBean(value=IsEnableJsCss.class)
public class CssController {
	
	private final Logger logger = LoggerFactory.getLogger(CssController.class);
	
	@Autowired
	private ICssManager cssManager;
	
	@Autowired
	private JsCssAutoConfiguration jsCssAutoConfiguration;
	
	/**
	 *  获取合并的css文件内容
	* <br>方法说明：                    getCss
	* <br>输入参数说明：           
	* <br>@param cssNames
	* <br>@param request
	* <br>@param response
	* <br>输出参数说明：
	* <br>void           
	*
	 */
	@RequestMapping(value="#{'${"+JsCssAutoConfiguration.css_uri+":}'?:'/css'}/{cssNames}",method={RequestMethod.GET,RequestMethod.POST})
    public void getCss(@PathVariable("cssNames") String cssNames,HttpServletRequest request,HttpServletResponse response){
	    this.getCss(cssNames, "UTF-8", request, response);
	}
	
	/**
	 * 获取合并的css文件内容
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="#{'${"+JsCssAutoConfiguration.css_uri+":}'?:'/css'}/encoding/{encoding}/{cssNames}",method={RequestMethod.GET,RequestMethod.POST})
	public void getCss(@PathVariable("cssNames") String cssNames,@PathVariable("encoding")String encoding,HttpServletRequest request,HttpServletResponse response){
		PrintWriter writer = null;
		try {
			String cssContent = this.cssManager.getCss(cssNames);
			
			response.reset();
			response.setBufferSize(2048);
			response.setCharacterEncoding(encoding);
			response.setContentLength(cssContent.getBytes(encoding).length);
			response.setContentType("text/css");
			response.setStatus(HttpServletResponse.SC_OK);
			writer = response.getWriter();
			writer.print(cssContent);
			writer.flush();
		} catch (Exception e) {
			this.logger.error("获取css文件失败："+e.getMessage(),e);
			try {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage());
			} catch (IOException e1) {
				this.logger.error(e1.getMessage(),e1);
			}
		}finally{
			if(writer != null){
				writer.close();
			}
		}
	}
	
	/**
	 * 刷新CSS缓存库
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="#{'${"+JsCssAutoConfiguration.refresh_css_uri+":}'?:'/refresh/css'}",method={RequestMethod.GET,RequestMethod.POST})
	public void refreshCss(HttpServletRequest request,HttpServletResponse response){
		PrintWriter writer = null;
		try {
			boolean refresh = this.cssManager.refresh();
			response.reset();
			response.setBufferSize(2048);
			response.setCharacterEncoding(this.jsCssAutoConfiguration.getEncoding());
			response.setContentType("text/html");
			response.setStatus(HttpServletResponse.SC_OK);
			writer = response.getWriter();
			writer.println("refresh css repertory status is "+refresh);
			writer.println("<br>3秒后自动跳转到CSS列表页面……");
			writer.printf("<br><a href=\"%1$s\">%2$s</a>",this.jsCssAutoConfiguration.getListCssUri(),"手动跳转  "+this.jsCssAutoConfiguration.getListCssUri());
			response.setHeader("refresh","3;URL="+this.jsCssAutoConfiguration.getListCssUri()+"");
			writer.flush();
		} catch (Exception e) {
			this.logger.error("刷新css缓存失败："+e.getMessage(),e);
			try {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage());
			} catch (IOException e1) {
				this.logger.error(e1.getMessage(),e1);
			}
		}finally{
			if(writer != null){
				writer.close();
			}
		}
	}
	
	/**
	 * 获取所有css缓存库中css文件名
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="#{'${"+JsCssAutoConfiguration.list_css_uri+":}'?:'/list/css'}",method={RequestMethod.GET,RequestMethod.POST})
	public void listCssMenu(HttpServletRequest request,HttpServletResponse response){
		PrintWriter writer = null;
		try {
			List<ResourcesBean> listResourcesBeans = this.cssManager.listResourcesBeans();
			
			response.reset();
			response.setBufferSize(2048);
			response.setCharacterEncoding(this.jsCssAutoConfiguration.getEncoding());
//			response.setContentLength(jsContent.length());
			response.setContentType("text/html");
			response.setStatus(HttpServletResponse.SC_OK);
			writer = response.getWriter();
			writer.println("<title>css文件列表（总计："+listResourcesBeans.size()+"条）</title>");
			writer.println("<style type=\"text/css\">a:link,a:visited{text-decoration:none;}tr:nth-child(2n){background-color: #E0FFFF;}tr:nth-child(2n+1){background-color:#FFFFFF;}</style>");
			writer.println("<h4>All css file name is (counts:"+listResourcesBeans.size()+"):</h4>");
			writer.println("<a href=\""+this.jsCssAutoConfiguration.getRefreshCssUri()+"\"><h4>Refresh css store</h4></a>");
			writer.println("<table>");
			for(ResourcesBean cssTmp:listResourcesBeans){
				writer.println("<tr>");
				writer.printf("<td><a href=\"%1$s\">%2$s</a></td>",this.jsCssAutoConfiguration.getCssUri()+"/"+cssTmp.getKeyName(),cssTmp.getFileFullName());
				writer.printf("<td>&nbsp;&nbsp;<a href=\"%1$s\">%2$s</a></td>",this.jsCssAutoConfiguration.getCssUri()+"/"+cssTmp.getKeyName(),cssTmp.getFileRelativePath());
				writer.printf("<td>&nbsp;&nbsp;<a href=\"%1$s\">%2$s</a></td>",this.jsCssAutoConfiguration.getCssUri()+"/encoding/UTF-8/"+cssTmp.getKeyName(),"UTF-8");
				writer.printf("<td>&nbsp;&nbsp;<a href=\"%1$s\">%2$s</a></td>",this.jsCssAutoConfiguration.getCssUri()+"/encoding/GBK/"+cssTmp.getKeyName(),"GBK");
				writer.println("</tr>");
				writer.flush();
			}
			writer.println("</table>");
		} catch (Exception e) {
			this.logger.error("获取css列表失败："+e.getMessage(),e);
			try {
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage());
			} catch (IOException e1) {
				this.logger.error(e1.getMessage(),e1);
			}
		}finally{
			if(writer != null){
				writer.close();
			}
		}
	}

}
